//
//  AppData.swift
//  MikerShop
//
//  Created by eme on 2016/12/7.
//  Copyright © 2016年 eme. All rights reserved.
//

import Foundation
import RealmSwift
import SwiftyUserDefaults
import UtilCore
import RickonCore
import NetWorkCore

extension DefaultsKeys {
    /// 缓存用户的主键id
    static let userid = DefaultsKey<String>("USERID")
    
}
public enum AppDataState{
    /// 当前状态为游客状态
    case tourists
    /// 审核未认证的状态
    case notAudit(user:UserModel)
    ///表示审核中
    case auditing(user:UserModel)
    ///表示审核失败
    case auditfailed(user:UserModel)
    ///已经审核通过
    case audited(user:UserModel)
}
/// App 整体数据配置
public class AppData: NSObject {
    public static var sharedInstance : AppData {
        struct Static {
            static let instance : AppData = AppData()
        }
        return Static.instance
    }
    ///用户信息
    public static var loginedUser:UserModel?{
        get{
            return  AppData.sharedInstance.user
        }
        set (newVal){
            AppData.sharedInstance.user = newVal
        }
    }
    public var user: UserModel?
    ///当前app的状态
    public static var appState:AppDataState{
        get{
            guard let user = AppData.loginedUser else {
                return .tourists
            }
            //thrState 1-正常(审核通过) 2-代理审核 3-入驻审核 4-冻洁 5-代理审核失败 6-入驻审核失
            switch user.thrState {
            case "1":
                return .audited(user: user)
            case "2","3":
                return .auditing(user: user)
            case "4","5","6":
                return .auditfailed(user: user)
            default:
                return .notAudit(user: user)
            }
        }
    }
    /**
     审核未通过之前，商品的进货价要用零售价替换
     */
    public static func getFinalShowPrice(jinPrice:Double,lingPrice:Double) -> Double {
        switch AppData.appState {
        case .audited:
            return jinPrice
        default:
            return lingPrice
        }
    }
    /**
     审核未通过之前，商品的进货价要用零售价替换
     */
    public static func getPriceImgName()-> String{
        switch AppData.appState {
        case .audited:
            return "jinprice"
        default:
            return "lingprice"
        }
    }
    ///更新用户信息
    public static func updateUserModel(_ user:UserModel) -> Void {
        AppData.loginedUser = user
        Defaults[.userid] = user.userid
        /// 用于更新极光推送的 tags
        _ = "jpushalias".openURL(["userid": user.userid])
        let realm = try! Realm()
        try! realm.write {
            realm.add(user, update: true)
        }
        /// 用户信息状态发生了改变，通知app修改对应的状态
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConfig.notification.appdatachangedKey), object: user)
    }
    /// 退出登录 ， 清空用户信息
    public static func loginOut() {
        AppData.loginedUser  = nil
        ///清除userid
        Defaults.remove(.userid)
        ///清除devid
        Defaults.remove(.uuid)
        NetWorkAPI.sharedInstance.headers.removeValue(forKey: "devid")
        let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
        let realmURLs = [
            realmURL,
            realmURL.appendingPathComponent("lock"),
            realmURL.appendingPathComponent("log_a"),
            realmURL.appendingPathComponent("log_b"),
            realmURL.appendingPathComponent("note")
        ]
        for URL in realmURLs {
            do {
                try FileManager.default.removeItem(at: URL)
            } catch {
                // 处理错误
            }
        }
    }
    override init() {
        let userid =  Defaults[.userid]
        if let realm = try? Realm(), userid.characters.count > 0{
            let user =  realm.object(ofType: UserModel.self, forPrimaryKey: userid)
            self.user =  user
        }else{
            let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
            let realmURLs = [
                realmURL,
                realmURL.appendingPathComponent("lock"),
                realmURL.appendingPathComponent("log_a"),
                realmURL.appendingPathComponent("log_b"),
                realmURL.appendingPathComponent("note")
            ]
            for URL in realmURLs {
                do {
                    try FileManager.default.removeItem(at: URL)
                } catch {
                    // 处理错误
                }
            }
        }
    }
}

